package com.youoor.mvc;

import com.youoor.common.utils.CommonUtils;
import com.youoor.common.utils.QiNiuUtils;
import com.youoor.domain.UserCard;
import com.youoor.domain.UserInfo;
import com.youoor.dto.RetDTO;
import com.youoor.enums.ErrorCodeEnum;
import com.youoor.exception.ServiceException;
import com.youoor.interceptors.RequestAttribute;
import com.youoor.service.UserCardService;
import com.youoor.service.UserService;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value={"/open", "/core", "/inner"}, produces={"application/json"})
public class UserController extends AbstractController
{
  private static final Logger logger = LoggerFactory.getLogger(UserController.class);

  @Autowired
  private UserService userService;

  @Autowired
  private UserCardService userCardService;

/*  @Autowired
  private HttpSession httpSession;*/

  @RequestMapping({"/register"})
  public RetDTO register(@RequestAttribute("userName") String userName, @RequestAttribute("email") String email, @RequestAttribute("password") String password)
  {
    if (verifyUserNameIsExsit(userName) != null) {
      throw new ServiceException(ErrorCodeEnum.CODE_YOUOOR_VERIFY_USERNMAE, "用户名已存在");
    }
    if (verifyEmailIsExist(email) != null) {
      throw new ServiceException(ErrorCodeEnum.CODE_YOUOOR_VERIFY_EMAIL, "用户邮箱已注册");
    }
    UserInfo userInfo = new UserInfo();
    Date nowTime = new Date();
    userInfo.setUsername(userName);
    userInfo.setEmail(email);
    String salt = CommonUtils.getRandomString(6);
    userInfo.setSalt(salt);
    userInfo.setPassword(CommonUtils.MD5Password(password, salt));
    Date nowDate = new Date();
    userInfo.setUtime(nowDate);
    userInfo.setCtime(nowDate);
    this.userService.save(userInfo);
    UserInfo loginUser = this.userService.login(userName, CommonUtils.MD5Password(password, userInfo.getSalt()));
    /**
     * 注册的时候默认先创建一个空卡片
     */
    UserCard userCard = new UserCard();
    userCard.setUserId(loginUser.getUserId());
    userCard.setName("有而卡");
    userCard.setLocation("地址");
    userCard.setOccupation("职业");
    userCard.setHobby("兴趣");
    userCard.setDescription("完善您的描述信息，让更多人了解您。");
    userCard.setBackground("bg_"+CommonUtils.getRandomInt(8)+".jpg");
    userCard.setCtime(nowTime);
	userCard.setUtime(nowTime);
	userCardService.createCard(userCard, null);
    this.httpSession.setAttribute(LOGIN_USER, loginUser);
    this.httpSession.setAttribute(LOGIN_CARD, userCard);
    RetDTO retDTO = new RetDTO();
    retDTO.addResult("loginCard", userCard);
    retDTO.markSuccess();
    return retDTO;
  }

  @RequestMapping({"/logout"})
  public RetDTO logout()
  {
    this.httpSession.removeAttribute(LOGIN_USER);
    this.httpSession.removeAttribute(LOGIN_CARD);
    RetDTO retDTO = new RetDTO();
    retDTO.addResult("result", "ok");
    retDTO.markSuccess();
    return retDTO;
  }

  @RequestMapping({"/login"})
  public RetDTO login(@RequestAttribute("userName") String userName, @RequestAttribute("password") String password)
  {
    UserInfo userInfo = verifyUserNameIsExsit(userName);
    if (userInfo == null) {
      throw new ServiceException(ErrorCodeEnum.CODE_YOUOOR_VERIFY_USERNMAE, "用户名不存在");
    }

    UserInfo loginUser = this.userService.login(userName, CommonUtils.MD5Password(password, userInfo.getSalt()));
    if (loginUser == null) {
      throw new ServiceException(ErrorCodeEnum.CODE_YOUOOR_VERIFY_PASSWORD);
    }
    UserCard userCard = this.userCardService.getUserCardByUserId(loginUser.getUserId());
    int cardFlag = 0;
    if (userCard != null) {
      cardFlag = 1;
      this.httpSession.setAttribute(LOGIN_CARD, userCard);
    }
    this.httpSession.setAttribute(LOGIN_USER, loginUser);

    RetDTO retDTO = new RetDTO();
    retDTO.addResult("result", Integer.valueOf(cardFlag));
    retDTO.markSuccess();
    return retDTO;
  }

  @RequestMapping({"/sendMailByYouoor"})
  public RetDTO sendMailByYouoor(@RequestAttribute("cardId") String toCardId, @RequestAttribute("title") String title, @RequestAttribute("content") String content){
	    UserCard userCard = userCardService.selectByPrimaryKey(Integer.valueOf(toCardId));
	    UserInfo userInfo = userService.selectByPrimaryKey(userCard.getUserId());
	 // Get system properties
	    Properties props = System.getProperties();
	 	String mailHost1="smtp.qq.com";
	 	String mailFrom1="service@youoor.com";
	 	//String mailTo1="guoxiaoliang0805@163.com";
	 	String mailAuthName1="service@youoor.com";
	 	String mailFromPass1="youoor12345678";
	    // Setup mail server
	    props.put("mail.smtp.host", mailHost1);

	    // Get session
	    props.put("mail.smtp.auth", "true"); //这样才能通过验证

	    MyAuthenticator myauth = new MyAuthenticator(mailAuthName1, mailFromPass1);
	    Session session = Session.getDefaultInstance(props, myauth);
	    // Define message
	    MimeMessage message = new MimeMessage(session);
	    try {
		    // Set the from address
		    message.setFrom(new InternetAddress(mailFrom1));
		    // Set the to address
		    message.addRecipient(Message.RecipientType.TO,
		      new InternetAddress(userInfo.getEmail()));
		    // Set the subject
		    message.setSubject(title+"","UTF-8");
		    StringBuffer sb = new StringBuffer();     
	        sb.append("<HTML>\n");     
	        sb.append("<HEAD>\n");     
	        sb.append("<TITLE>\n");     
	        sb.append(title+ "\n");     
	        sb.append("</TITLE>\n");     
	        sb.append("</HEAD>\n");     
	
	        sb.append("<BODY>\n");     
	        sb.append("<H3>" + content + "</H3>" + "\n");     
	
	        sb.append("\n");     
	
	        sb.append("</BODY>\n");     
	        sb.append("</HTML>\n");    
       
			message.setDataHandler(new DataHandler(new ByteArrayDataSource(sb.toString(), "text/html;charset=UTF-8")));
			Transport.send(message);
		}  catch (Exception e) {
			e.printStackTrace();
		} 
	
	  	RetDTO retDTO = new RetDTO();
	    retDTO.addResult("result", "ok");
	    retDTO.markSuccess();
	    return retDTO;
  }
  
  @RequestMapping({"/modifyPwd"})
  public RetDTO modifyPwd(@RequestAttribute("oldPwd") String oldPwd, @RequestAttribute("newPwd") String newPwd) {
	   UserInfo userInfo = getCurrUser();
	   if (!userInfo.getPassword().equals(CommonUtils.MD5Password(oldPwd, userInfo.getSalt()))) {
		   throw new ServiceException(ErrorCodeEnum.CODE_YOUOOR_VERIFY_OLD_PASSWORD);
	   }
	   Date nowDate = new Date();
	   String salt = CommonUtils.getRandomString(6);
       userInfo.setSalt(salt);
       userInfo.setPassword(CommonUtils.MD5Password(newPwd, salt));
       userInfo.setUtime(nowDate);
       userService.updateByPrimaryKey(userInfo);
       this.httpSession.setAttribute(LOGIN_USER, userInfo);
	   RetDTO retDTO = new RetDTO();
	   retDTO.addResult("result", "ok");
	   retDTO.markSuccess();
	   return retDTO;
  } 
  
  @RequestMapping({"/getUpToken"})
  public RetDTO getUpToken() {
    Map retMap = new HashMap();
    RetDTO retDTO = new RetDTO();
    retDTO.addResult("uptoken", QiNiuUtils.getUpToken());
    retDTO.markSuccess();
    return retDTO;
  }

  private UserInfo verifyUserNameIsExsit(String userName)
  {
    return this.userService.getUserByName(userName);
  }

  private UserInfo verifyEmailIsExist(String email)
  {
    return this.userService.getUserByEmail(email);
  }
}